/* eslint-disable @typescript-eslint/explicit-member-accessibility */
// eslint-disable-next-line no-var, @typescript-eslint/no-invalid-this
var __assign =
	// eslint-disable-next-line @typescript-eslint/no-invalid-this
	(this && this.__assign) ||
	function () {
		__assign =
			Object.assign ||
			function (t) {
				// eslint-disable-next-line no-var, no-inner-declarations
				for (var s, i = 1, n = arguments.length; i < n; i++) {
					s = arguments[i];
					for (let p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
				}
				return t;
			};
		// eslint-disable-next-line @typescript-eslint/no-invalid-this
		return __assign.apply(this, arguments);
	};
// MathJax配置文件 - 独立管理MathJax相关配置
define('mathjax-config', ['require', 'exports'], (_require, exports) => {
	Object.defineProperty(exports, '__esModule', { value: true });
	exports.getMathJaxPath = getMathJaxPath;
	exports.loadMathJax = loadMathJax;
	/**
	 * 获取MathJax库的CDN路径
	 * @returns MathJax库的CDN路径字符串
	 */
	function getMathJaxPath() {
		// 使用CDN路径提供稳定访问
		return 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
	}
	// 已移至文件顶部定义
	/**
	 * MathJaxService类 - 管理MathJax的加载和渲染
	 */
	// eslint-disable-next-line tsdoc/syntax
	let MathJaxService = /** @class */ (function () {
		/**
		 * 构造函数
		 */
		class MathJaxService {
			constructor() {
				// 初始化状态属性
				this._isLoaded = !!window.MathJax;
				this._isLoading = false;
				this._readyCallbacks = [];
				this._errorCallbacks = [];
				// 获取MathJax CDN路径
				this._mathJaxPath = getMathJaxPath();
			}
			/**
			 * 设置MathJax配置
			 * @param customConfig - 自定义配置对象
			 */
			setupConfig(customConfig) {
				// eslint-disable-next-line @typescript-eslint/no-this-alias
				let _this = this;
				// 基础配置
				let baseConfig = {
					tex: {
						inlineMath: [
							['$', '$'],
							['\\(', '\\)'],
						],
						displayMath: [
							['$$', '$$'],
							['\\[', '\\]'],
						],
						processEscapes: true,
						tags: 'none', // 不显示公式标签
					},
					svg: {
						fontCache: 'global',
						mtextInheritFont: true,
						scale: 1.0, // 公式缩放比例
						minScale: 0.5, // 最小缩放比例
						maxScale: 2.0, // 最大缩放比例
					},
					chtml: {
						// 启用web字体
						fontURL: 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/output/chtml/fonts/woff-v2',
						matchFontHeight: false,
					},
					// 配置加载器
					loader: {
						load: ['[tex]/html'],
						// 使用CDN默认路径
						source: {
							'[tex]/html': '[tex]/html',
						},
					},
					startup: {
						typeset: true,
						// 使用箭头函数确保this指向正确
						pageReady: function () {
							return _this._handleReady();
						},
					},
				};
				// 合并自定义配置
				let mergedConfig = this._deepMerge(baseConfig, customConfig || {});
				// 设置全局配置
				window.MathJax = mergedConfig;
			}
			/**
			 * 加载MathJax库
			 * @param customConfig - 自定义配置对象
			 * @returns 实例自身，支持链式调用
			 */
			load(customConfig) {
				// eslint-disable-next-line @typescript-eslint/no-this-alias
				let _this = this;
				// 避免重复加载
				if (this._isLoading || this._isLoaded) {
					if (this._isLoaded) {
						this._executeReadyCallbacks();
					}
					return this;
				}
				this._isLoading = true;
				try {
					// 设置配置
					this.setupConfig(customConfig);
					// 移除已存在的MathJax脚本
					let existingScript = document.querySelector('script[src*="mathjax"]');
					if (existingScript) {
						existingScript.remove();
					}
					// 直接从CDN加载
					let script = document.createElement('script');
					script.src = this._mathJaxPath;
					script.async = true;
					script.onload = function () {
						_this._isLoading = false;
						_this._isLoaded = true;
						console.log('MathJax loaded successfully from CDN');
						_this._executeReadyCallbacks();
					};
					script.onerror = function (err) {
						_this._isLoading = false;
						console.error('Failed to load MathJax from CDN:', err);
						_this._executeErrorCallbacks(err instanceof Error ? err : new Error(String(err)));
					};
					// 将脚本添加到文档头部
					document.head.appendChild(script);
				} catch (error) {
					this._isLoading = false;
					console.error('Error during MathJax setup:', error);
					this._executeErrorCallbacks(error instanceof Error ? error : new Error(String(error)));
				}
				return this;
			}
			/**
			 * 渲染公式
			 * @param elements - 要渲染的元素
			 * @returns 实例自身，支持链式调用
			 */
			typeset(elements) {
				// eslint-disable-next-line no-void
				if (elements === void 0) {
					elements = null;
				}
				if (!this._isLoaded || !window.MathJax || !window.MathJax.typeset) {
					console.warn('MathJax is not loaded yet, queuing typeset operation');
					// 如果MathJax未加载完成，将排版操作加入回调队列
					this.onReady(() => {
						if (window.MathJax && window.MathJax.typeset) {
							window.MathJax.typeset(elements);
						}
					});
					return this;
				}
				try {
					window.MathJax.typeset(elements);
				} catch (error) {
					console.error('Error during MathJax typesetting:', error);
				}
				return this;
			}
			/**
			 * 添加就绪回调
			 * @param callback - 回调函数
			 * @returns 实例自身，支持链式调用
			 */
			onReady(callback) {
				if (typeof callback !== 'function') {
					console.error('MathJax onReady: callback must be a function');
					return this;
				}
				if (this._isLoaded) {
					// 如果已经加载完成，立即执行回调
					setTimeout(() => {
						try {
							callback();
						} catch (error) {
							console.error('Error in MathJax ready callback:', error);
						}
					}, 0);
				} else {
					// 否则添加到回调队列
					this._readyCallbacks.push(callback);
				}
				return this;
			}
			/**
			 * 添加错误回调
			 * @param callback - 回调函数
			 * @returns 实例自身，支持链式调用
			 */
			onError(callback) {
				if (typeof callback !== 'function') {
					console.error('MathJax onError: callback must be a function');
					return this;
				}
				this._errorCallbacks.push(callback);
				return this;
			}
			/**
			 * 重新初始化MathJax
			 * @returns 实例自身，支持链式调用
			 */
			reset() {
				this._isLoaded = false;
				this._isLoading = false;
				this._readyCallbacks = [];
				this._errorCallbacks = [];
				if (window.MathJax) {
					delete window.MathJax;
				}
				return this;
			}
			/**
			 * 获取当前状态
			 * @returns 状态对象
			 */
			getStatus() {
				return {
					isLoaded: this._isLoaded,
					isLoading: this._isLoading,
					readyCallbackCount: this._readyCallbacks.length,
					errorCallbackCount: this._errorCallbacks.length,
				};
			}
			/**
			 * 深度合并配置对象
			 * @param target - 目标对象
			 * @param source - 源对象
			 * @returns 合并后的对象
			 */
			_deepMerge(target, source) {
				// eslint-disable-next-line @typescript-eslint/no-this-alias
				let _this = this;
				let output = { ...target };
				if (this._isObject(target) && this._isObject(source)) {
					Object.keys(source).forEach((key) => {
						let _a;
						let _b;
						if (_this._isObject(source[key])) {
							if (!(key in target)) {
								Object.assign(output, ((_a = {}), (_a[key] = source[key]), _a));
							} else {
								output[key] = _this._deepMerge(target[key], source[key]);
							}
						} else {
							Object.assign(output, ((_b = {}), (_b[key] = source[key]), _b));
						}
					});
				}
				return output;
			}
			/**
			 * 检查是否为对象
			 * @param item - 待检查项
			 * @returns 是否为对象
			 */
			// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
			_isObject(item) {
				return item && typeof item === 'object' && !Array.isArray(item);
			}
			/**
			 * 当MathJax准备就绪时执行
			 * @returns Promise对象
			 */
			_handleReady() {
				this._isLoaded = true;
				this._isLoading = false;
				this._executeReadyCallbacks();
				return window.MathJax.startup.defaultPageReady();
			}
			/**
			 * 执行所有就绪回调
			 */
			_executeReadyCallbacks() {
				this._readyCallbacks.forEach((callback) => {
					try {
						callback();
					} catch (error) {
						console.error('Error in MathJax ready callback:', error);
					}
				});
				// 清空回调列表
				this._readyCallbacks = [];
			}
			/**
			 * 执行所有错误回调
			 * @param error - 错误对象
			 */
			_executeErrorCallbacks(error) {
				this._errorCallbacks.forEach((callback) => {
					try {
						callback(error);
					} catch (err) {
						console.error('Error in MathJax error callback:', err);
					}
				});
				// 保留错误回调，以便后续错误也能被处理
			}
		}
		return MathJaxService;
	})();
	// 创建单例实例
	let mathJaxService = new MathJaxService();
	// 简化的加载函数，保持向后兼容
	function loadMathJax() {
		// 直接返回接口类型，避免私有属性暴露
		return mathJaxService;
	}
	// 暴露给全局的方法和服务
	window.getMathJaxPath = getMathJaxPath;
	window.loadMathJax = loadMathJax;
	// 避免类型冲突
	window.MathJaxService = MathJaxService;
	window.mathJaxService = mathJaxService;
});
